import mpx from '@mpxjs/core'
import mpxFetch from '@mpxjs/fetch'
import { baseUrl } from './config'
import { logout } from './auth'
mpx.use(mpxFetch)

mpx.xfetch.interceptors.request.use(function (config) {
  const token = wx.getStorageSync('token')
  if (token) {
    config.headers = {
      Authorization: token
    }
  }
  // 也可以返回promise
  return config
})
// mpx.xfetch.interceptors.response.use(function (res) {
// if (res.data.code === 200) {
//   return res
// } else if (res.data.code === 22) {
//   logout()
//   return false
// } else if (res.data.code === 500) {
//   wx.showToast({
//     title: res.data.msg,
//     icon: 'none'
//   })
//   return false
// }
// console.log(res)
// })
const request = ({ url, method = 'get', data, isThirdParty = false }) => {
  const cancelToken = new mpx.xfetch.CancelToken()
  return new Promise((resolve, reject) => {
    // 设置一个定时器，超时后调用abort方法结束当前请求
    const tid = setTimeout(() => {
      // console.error(`Fetch timeout: ${url}`)
      cancelToken.exec('超时取消请求')
    }, 12000)
    if (isThirdParty) {
      return mpx.xfetch.fetch({
        url,
        data,
        method,
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        usePre: false,
        cancelToken: cancelToken.token
      }).then((response) => {
        // eslint-disable-next-line no-empty
        switch (~~response.statusCode) {
          case 200:
            resolve(response.data)
            break
          case 500:
            wx.showToast({
              title: response.errMsg,
              icon: 'none'
            })
            reject(response)
            break
        }
      }).catch((err) => {
        reject(err)
      })
    }
    mpx.xfetch.fetch({
      url: baseUrl + url,
      data,
      method,
      usePre: false,
      cancelToken: cancelToken.token
    }).then((response) => {
      // eslint-disable-next-line no-empty
      switch (~~response.data.code) {
        case 200:
          resolve(response.data.data)
          break
        case 205:
          resolve(response.data.data)
          break
        case 22:
          logout()
          reject(response.data.data)
          break
        case 500:
          wx.showToast({
            title: response.data.msg,
            icon: 'none'
          })
          reject(response)
          break
      }
    }).catch((err) => {
      // console.log('err 加载超时', err)
      wx.showToast({
        title: '加载超时，请稍后重试',
        icon: 'none'
      })
      reject(err)
    }).finally(() => {
      clearTimeout(tid) // 得到请求结果后，要清除定时器
    })
  })
}
export default request
